<template>
	<view>
		<u-upload :fileList="fileList" @customPreview="customPreview" :name="name" :previewFullImage="true" @afterRead="afterRead"
			@delete="deletePic" multiple :maxCount="isEdit?limit:fileList.length" :deletable="deletable">
		</u-upload>
	</view>
</template>

<script>
	import {
		uploadMedia
	} from '@/common/api/index.js'
	import configService from '@/common/service/config.service.js'
	export default {
		name: "uploadMedia", //上传多媒体
		props: {
			name: {
				type: String,
				default: '1'
			},
			limit: {
				type: Number,
				default: 1
			}, // 最大允许上传个数
			value: {
				type: String | Number
			},
			deletable: {
				type: Boolean,
				default: true, //是否显示删除按钮
			},
			isEdit: {
				type: Boolean,
				default: true, //是否可编辑
			}
		},
		watch: {
			value: {
				handler(newVal) {
					this.fileList = [] //初始化
					if (newVal) {
						let newValList = newVal.indexOf(",") != -1 ? newVal.split(",") : [newVal]
						newValList.forEach((item, index) => {
							this.fileList[index] = {
								type: 'image',
								url: configService.staticDomainURL + item,
								id: item
							}
						});
						console.log("图片",this.fileList)
					}
				},
				immediate: true
			}
		},
		data() {
			return {
				fileList: [], //默认上传图
				previewShow: false, //图片预览显示
				previewImg: '', //预览地址
			};
		},
		methods: {
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				let filesIds = []; //需要传回父组件的文件id
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].thumb)
					let item = this.fileList[fileListLen]
					console.log("图片",result)
					const datas = result.data
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
					    url:  `${datas.id}`,
					    id: `${datas.id}`,
					}))
					fileListLen++
				}
				this.fileList.forEach(item => {
					if (item) {
						// 需要传回的图片地址
						filesIds.push(`${item.id}`) 
					}
				})
				this.$emit("input", filesIds.length > 0 ? filesIds.toString() : '') //传回父组件
			},
			uploadFilePromise(url) {
				let that = this
				return new Promise(function(resolve, reject) {
					uni.uploadFile({
						url: uploadMedia,
						header:{
							'token':that.$store.state.vuex_token
						},
						filePath: url,
						name: 'file',
						success: (res) => {
							console.log("上次图片成功",res.data)
							resolve(JSON.parse(res.data));
						},
						fail: (err) => {
							reject(err);
						},
						complete() {
							uni.hideLoading();
						}
					});
				})
			},
			// 删除图片
			deletePic(event) {
				//1 delfileId 获取移除的id 2 获取未被移除的id数组传回父组件
				let delfileId = this.fileList[event.index].id
				let filesIds = []
				this.fileList.forEach(item => {
					if (item.id !== delfileId) {
						filesIds.push(item.id)
					}
				})
				this.$emit("input", filesIds.length > 0 ? filesIds.toString() : '') //传回父组件
			},
			//自定义点击图片事件，用于自定义预览图片
			customPreview(event) {
				let imgUrls = this.fileList.map(item=>{return item.url})
				uni.previewImage({
					current:imgUrls.indexOf(event.url), //判断当前显示哪一张
					urls: imgUrls
				})
			}
			
		}
	}
</script>

<style>
	.images {
		width: 100px;
		height: 100px;
	}
</style>
